package com.gzsxy.sso.core.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gzsxy.sso.common.dto.request.RoleRequest;
import com.gzsxy.sso.common.dto.request.UserRequest;
import com.gzsxy.sso.common.dto.response.UserRsp;
import com.gzsxy.sso.common.result.R;
import com.gzsxy.sso.core.entity.Permission;
import com.gzsxy.sso.core.entity.User;
import com.gzsxy.sso.core.entity.vo.UserQueryVo;
import com.gzsxy.sso.core.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 *  用户管理
 * @author zxl
 * @since 2021-11-10
 */
@Api(description = "用户管理")
@CrossOrigin  //解决跨域
@RestController
@RequestMapping("/admin/user")
public class UserController {

    @Autowired
    private UserService userService;


    @ApiOperation("根据用户id查询用户")
    @GetMapping("/getUserById/{id}")
    public R getUserById(@ApiParam("id") @PathVariable String id){
        User user = userService.getUserById(id);
        return R.ok().message("查询成功").data("user",user);
    }


    @ApiOperation("根据用户名查询用户")
    @GetMapping("/getUserByUserName")
    public R getUserByUserName(@ApiParam("用户名") @RequestParam String username){
        User user = userService.findByUsername(username);
        return R.ok().message("查询成功").data("user",user);
    }

    @ApiOperation("根据身份证号查询用户")
    @GetMapping("/getUserByIdCard")
    public R getUserByIdCard(@ApiParam("身份证号") @RequestParam String idcard){
        User user = userService.findByIdCard(idcard);
        return R.ok().message("查询成功").data("user",user);
    }


    @ApiOperation("根据用户名查询当前用户的所有权限")
    @GetMapping("/getPermissionByUsername")
    public R getPermissionByUsername(@ApiParam("用户名") @RequestParam String username){
        List<Permission> permission = userService.findPermissionByUsername(username);
        return R.ok().message("查询成功").data("permission",permission);
    }

    @ApiOperation("查询所有用户")
    @GetMapping("/getAllUser")
    public R getAllUser(){
        List<User> user = userService.getAllUser();
        return R.ok().message("查询成功").data("user",user);
    }

    @ApiOperation("新增用户")
    @PostMapping("/addUser")
    public R addUser(@RequestBody UserRequest user){
        userService.addUser(user);
        return R.ok().message("添加成功");
    }

    @ApiOperation("编辑用户")
    @PutMapping("/update")
    public R updateUser(@RequestBody UserRequest request){
        userService.updateUser(request);
        return R.ok().message("更新成功");
    }


    @ApiOperation("用户分页列表查询")
    @GetMapping("/list")                       //required表示必须要填
    public R searchPageUser(@ApiParam(value = "当前页面",required = true,defaultValue ="1" ) @RequestParam Long page,         //long数据类型适用于较大整数类型
                            @ApiParam(value = "每页记录数",required = true,defaultValue ="5") @RequestParam Long limit,
                            @ApiParam("查询对象") UserQueryVo userQueryVo){

        IPage<?> pageParam = new Page<>(page, limit);
        IPage<UserRsp> userIPage = userService.selectPage(pageParam,userQueryVo);
        //获取查询的总结果
        List<UserRsp> records = userIPage.getRecords();
        //总记录数
        long total = userIPage.getTotal();
        //之所以ok（）方法后面还可以加方法是因为ok方法返回是r对象，对象又可以调用他的方法
        return R.ok().data("total",total).data("row",records);

    }

    @ApiOperation("删除用户")
    @DeleteMapping("/delete/{id}")
    public R deleteUser(@ApiParam("用户id") @PathVariable String id){
        Boolean flag = userService.deleteById(id);
        if (flag){
            return R.ok().message("删除成功");
        }
        return R.error().message("删除失败");
    }


    @ApiOperation("查询用户是否为超级管理员")
    @PostMapping("/isSadmin")
    public R isSadmin(@RequestBody UserRequest request){
        Boolean flag = userService.isSadmin(request.getId());
        if (flag){
            return R.ok().message("该用户是管理员");
        }
        return R.error().message("该用户不是管理员");
    }

    @ApiOperation("禁用账号")
    @PutMapping("/users/{userId}/state/{type}")
    public R accountDisable(@ApiParam(value = "用户id",required = true) @PathVariable String userId,
                            @ApiParam(value = "禁用类型",required = true) @PathVariable Boolean type){
        userService.changeDisabled(userId,type);
        return R.ok().message("成功");
    }




    @ApiOperation("根据关键字查询用户名列表")
    @GetMapping("/list/name/{key}")
    public R selectNameListByKey(
            @ApiParam(value = "关键字",required = true)
            @PathVariable String key){
        List<Map<String,Object>> nameList = userService.selectNameListByKey(key);
        return R.ok().data("nameList",nameList);
    }


    @ApiOperation("根据id批量删除用户")
    @DeleteMapping("batch-remove")
    public R removeRows(
            @ApiParam(value = "用户ID列表",required = true)
            @RequestBody List<String> idList){
        boolean result = userService.removeByIds(idList);
        if (result){
            return R.ok().message("删除成功");
        } else {
            return R.error().message("删除失败");
        }
    }


    @ApiOperation("更新用户最后登录时间")
    @GetMapping("/updateLastloginTime/{id}")
    public R updateLastloginTime(@PathVariable String id){
        userService.updateLastloginTime(id);
        return R.ok().message("更新成功");
    }



    @ApiOperation("修改密码")
    @PutMapping("/changePassword")
    public R changePassword(@RequestBody UserRequest userRequest){
        userService.changePassword(userRequest.getOldPassword(),userRequest.getPassword());
        return R.ok().message("修改成功");
    }



    @ResponseBody
    @GetMapping("/user")
    public String test1(){
        return "我是user";
    }

    @ResponseBody
    @GetMapping("/product")
    public String test2(String username){
        return "我是product";
    }


    /**
     * 登录功能
     *
     * @return
     */
    @PostMapping("login")
    public R login() {
        return R.ok().data("token", "admin");
    }



    /**
     * 获取用户信息
     *
     * @return
     */
    @GetMapping("info")
    public R info() {
        return R.ok().data("name", "admin")
                .data("roles", "[admin]")
                .data("avatar", "https://gd1.alicdn.com/imgextra/i4/0/O1CN015XW4gn1sdPV9MujsG_!!0-item_pic.jpg_400x400.jpg"); //头像
    }
}

